﻿/*
 * Created by SharpDevelop.
 * User: Heikki
 * Date: 22.11.2007
 * Time: 19:25
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections;
using System.Data.SQLite;
using System.ComponentModel;

namespace notebooklet
{
	public class Todos : IDataCtrl<Todo>, IEnumerator, IEnumerable
	{
		private SQLiteConnection db;
		private ArrayList todos;
		
		public Todos(SQLiteConnection db)
		{
			todos = new ArrayList();
			this.db = db;
		}
		
		public bool load() {
			SQLiteCommand cmd = db.CreateCommand();
			SQLiteDataReader data;
			
			cmd.CommandText = "SELECT * FROM todos";
			data = cmd.ExecuteReader();
			
			while ( data.Read() ) {
				object[] values = new object[data.FieldCount];
				data.GetValues(values);
				
				Todo todo = new Todo(db);
				todo.load(values);
				todos.Add(todo);
			}
			
			return true;
		}
		
		public bool save() {
			foreach ( Todo todo in todos ) {
				if ( !todo.save() ) { return false; }
			}
			
			return true;
		}
		
		public int count() { return todos.Count; }
		
		public bool add(Todo todo) {
			this.todos.Add(todo);
			return true;
		}
		
		public Todo get(int id) {
			foreach ( Todo todo in this.todos ) {
				if ( todo.Id == id ) { return todo; }
			}
			
			return null;
		}		
		
		// TODO: Aluksi copypaste, myöhemmin jaettuna koodina
		public int getNextId() {
			SQLiteCommand cmd = db.CreateCommand();
			SQLiteDataReader data;
			
			cmd.CommandText = "SELECT id FROM todosSeq";
			data = cmd.ExecuteReader();
			data.Read();
			int nextId = System.Convert.ToInt32(data["id"].ToString());
			data.Close();
			
			cmd.CommandText = "UPDATE usersSeq SET id = id + 1";
			cmd.ExecuteNonQuery();
			
			return nextId;
		}
		
		public SQLiteConnection getDb() { return this.db; }
		
		#region Iterator
		private int iterCurrent;
		
		public IEnumerator GetEnumerator() { return (IEnumerator)this; }
		public void Reset() { this.iterCurrent = -1; }
		public bool MoveNext() { return (++this.iterCurrent < this.todos.Count); }
		public object Current {
			get { return this.todos[this.iterCurrent]; }
		}
		#endregion Iterator
	}
}
